{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Python迭代器及其用法\n",
    "要自定义实现一个迭代器，则类中必须实现如下 2 个方法：\n",
    "1. __next__(self)：返回容器的下一个元素。\n",
    "2. __iter__(self)：该方法返回一个迭代器（iterator）。"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "class ListDemo(object):\n",
    "    def __init__(self):\n",
    "        self.__data = []\n",
    "        self.__step = 0\n",
    "\n",
    "    def __next__(self):\n",
    "        if self.__step <= 0:\n",
    "            raise StopIteration\n",
    "        self.__step -= 1\n",
    "        # 返回下一个元素\n",
    "        return self.__data[self.__step]\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self\n",
    "\n",
    "    def __setitem__(self, key, value):\n",
    "        self.__data.insert(key, value)\n",
    "        self.__step += 1\n",
    "\n",
    "mylist = ListDemo()\n",
    "mylist[0] = 1\n",
    "mylist[1] = 2\n",
    "for i in mylist:\n",
    "    print(i)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "Python 内置的 iter() 函数也会返回一个迭代器，该函数的语法格式如下：\n",
    "> iter(obj[, sentinel])\n",
    "\n",
    "其中，obj 必须是一个可迭代的容器对象，而 sentinel 作为可选参数，如果使用此参数，要求 obj 必须是一个可调用对象"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "myIter = iter([1, 2, 3])\n",
    "print(myIter.__next__())\n",
    "print(next(myIter))\n",
    "print(next(myIter))\n",
    "print(next(myIter))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "这里介绍 iter() 函数第 2 个参数的作用，如果使用该参数，则要求第一个 obj 参数必须传入可调用对象（可以不支持迭代），这样当使用返回的迭代器调用 __next__() 方法时，它会通过执行 obj() 调用 __call__() 方法，如果该方法的返回值和第 2 个参数值相同，则输出 StopInteration 异常；反之，则输出 __call__() 方法的返回值。"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%% md\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    },
    {
     "ename": "StopIteration",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mStopIteration\u001B[0m                             Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[7], line 20\u001B[0m\n\u001B[0;32m     18\u001B[0m a \u001B[38;5;241m=\u001B[39m \u001B[38;5;28miter\u001B[39m(mylist, \u001B[38;5;241m1\u001B[39m)\n\u001B[0;32m     19\u001B[0m \u001B[38;5;28mprint\u001B[39m(a\u001B[38;5;241m.\u001B[39m\u001B[38;5;21m__next__\u001B[39m())\n\u001B[1;32m---> 20\u001B[0m \u001B[38;5;28mprint\u001B[39m(\u001B[43ma\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[38;5;21;43m__next__\u001B[39;49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m)\n",
      "\u001B[1;31mStopIteration\u001B[0m: "
     ]
    }
   ],
   "source": [
    "class ListDemo(object):\n",
    "    def __init__(self):\n",
    "        self.__data = []\n",
    "        self.__step = 0\n",
    "\n",
    "    def __setitem__(self, key, value):\n",
    "        self.__data.insert(key, value)\n",
    "        self.__step += 1\n",
    "\n",
    "    def __call__(self):\n",
    "        self.__step -= 1\n",
    "        return self.__data[self.__step]\n",
    "\n",
    "mylist = ListDemo()\n",
    "mylist[0] = 1\n",
    "mylist[1] = 2\n",
    "\n",
    "a = iter(mylist, 1)\n",
    "print(a.__next__())\n",
    "print(a.__next__())\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}